package base.shiro.demo.session;

import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.SimpleSession;
import org.apache.shiro.session.mgt.eis.CachingSessionDAO;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.*;

/**
 * 自定义CachingSessionDAO
 */
@Component
public class ShiroSessionDao extends CachingSessionDAO {
    private Serializable sessionId;
    private RedisTemplate<String, Object> redisTemplate;
    private CustomSessionIdGenerator customSessionIdGenerator;



    /**
     * @param
     * @method 提供缓存session的扩展方法，到时候用的时候，
     * 想用什么缓存session信息，直接注入对应的CacheManager就行
     */
    public ShiroSessionDao(CacheManager cacheManager, RedisTemplate<String, Object> redisTemplate, CustomSessionIdGenerator customSessionIdGenerator ) {
        super.setCacheManager(cacheManager);
        this.redisTemplate = redisTemplate;
        this.customSessionIdGenerator = customSessionIdGenerator;
    }

    @Override
    protected void doUpdate(Session session) {
        System.out.println("更新session");
    }

    @Override
    protected void doDelete(Session session) {

        System.out.println("删除session");
    }

    @Override
    protected Serializable doCreate(Session session) {
        sessionId = customSessionIdGenerator.generateId(session);
        assignSessionId(session, sessionId);
        return sessionId;
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
        System.out.println("读取session");
        return null;
    }

    /**
     * @param
     * @method 把session对象转化为byte保存到redis中
     */
    public byte[] sessionToByte(Session session) {
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        byte[] bytes = null;
        try {
            ObjectOutputStream oo = new ObjectOutputStream(bo);
            oo.writeObject(session);
            bytes = bo.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bytes;
    }

    // 把byte还原为session
    public Session byteToSession(byte[] bytes){
        ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
        ObjectInputStream in;
        SimpleSession session = null;
        try {
            in = new ObjectInputStream(bi);
            session = (SimpleSession) in.readObject();
        } catch (ClassNotFoundException | IOException e) {
            e.printStackTrace();
        }

        return session;
    }
}
